/**
 * Copyright (c) 2017-2020 四川智慧云天 All rights reserved.
 *
 * https://www.sczhyt.cn
 *
 * 版权所有，侵权必究！
 */

package cn.sczhyt.modules.sys.service.impl;

import cn.sczhyt.common.utils.R;
import cn.sczhyt.modules.sys.dao.SysOrganizeInfoDao;
import cn.sczhyt.modules.sys.entity.SysOrganizeInfoEntity;
import cn.sczhyt.modules.sys.entity.SysUserRoleEntity;
import cn.sczhyt.modules.sys.entity.vo.SysDelegationUserInfoVOEntity;
import cn.sczhyt.modules.sys.entity.vo.SysUserVo1Entity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.Constant;
import cn.sczhyt.modules.sys.dao.SysUserDao;
import cn.sczhyt.modules.sys.entity.SysUserEntity;
import cn.sczhyt.modules.sys.service.SysRoleService;
import cn.sczhyt.modules.sys.service.SysUserRoleService;
import cn.sczhyt.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserDao userDao;
	@Autowired
	private SysOrganizeInfoDao sysOrganizeInfoDao;
	@Override
	public List<String> queryAllPerms(String userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<String> queryAllMenuId(String userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void saveUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(SysUserEntity user) {
//		if(StringUtils.isBlank(user.getPassword())){
//			user.setPassword(null);
//		}else{
//			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
//		}
		this.updateById(user);
		//修改SysOrganizeInfoEntity表
		SysOrganizeInfoEntity organizeInfoEntity = new SysOrganizeInfoEntity();
		organizeInfoEntity.setOrganizeName(user.getUsername());
		organizeInfoEntity.setMobile(user.getMobile());
		organizeInfoEntity.setEmail(user.getEmail());
		sysOrganizeInfoDao.update(organizeInfoEntity,new QueryWrapper<SysOrganizeInfoEntity>().eq("user_id",user.getUserId()));
	}

	@Override
	public void deleteBatch(String[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(String userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

	@Override
	public SysUserEntity queryByMobile(String mobile) {


		return userDao.queryByMobile(mobile);
	}

	@Override
	public boolean adminResetPassword(String userId, String password) {

		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(password);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

	@Override
	public SysUserEntity queryByUserId(String userId) {
		return userDao.selectById(userId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateStatus(String userId) {
		SysUserEntity userEntity = userDao.selectById(userId);

		if (userEntity == null) {
			return R.error(201,"用户不存在");
		}
		if (userEntity.getStatus() == 1) {
			userEntity.setStatus(0);
			userDao.updateById(userEntity);
			return R.ok();
		}
		if (userEntity.getStatus() == 0){
			userEntity.setStatus(1);
			userDao.updateById(userEntity);
			return R.ok();
		}

		return R.ok();
	}

	@Override
	public IPage<SysUserEntity> list(Integer page, Integer limit, SysUserVo1Entity userEntity) {
		Page<SysUserEntity> pages = new Page<>(page, limit);

		return userDao.list(pages,userEntity,Constant.ADMIN);
	}

	@Override
	public IPage<SysUserEntity> listByRoleId(Integer page, Integer limit, SysUserVo1Entity userEntity) {
		Page<SysUserEntity> pages = new Page<SysUserEntity>(page, limit);

		return userDao.list(pages,userEntity,Constant.DELEGATION);
	}

	@Override
	@Transactional
	public void saveUserToDelegation(SysUserVo1Entity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		SysUserEntity userEntity = new SysUserEntity();
		BeanUtils.copyProperties(user,userEntity);
		this.save(userEntity);
		//sysorganizeInfoEntity表新增数据
		SysOrganizeInfoEntity organizeInfoEntity = new SysOrganizeInfoEntity();
		organizeInfoEntity.setUserId(userEntity.getUserId());
		organizeInfoEntity.setOrganizeName(userEntity.getUsername());
		organizeInfoEntity.setMobile(userEntity.getMobile());
		organizeInfoEntity.setEmail(userEntity.getEmail());
		sysOrganizeInfoDao.insert(organizeInfoEntity);

		//检查角色是否越权
		checkRole(userEntity);

		//保存用户与角色关系
		List<String> roleList =null;
		roleList.add(Constant.DELEGATION);
		sysUserRoleService.saveOrUpdate(userEntity.getUserId(), roleList);
	}

	@Override
	@Transactional
	public void saveUserToAdmin(SysUserVo1Entity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		SysUserEntity userEntity = new SysUserEntity();
		BeanUtils.copyProperties(user,userEntity);
		this.save(userEntity);
		//sysorganizeInfoEntity表新增数据
		SysOrganizeInfoEntity organizeInfoEntity = new SysOrganizeInfoEntity();
		organizeInfoEntity.setUserId(userEntity.getUserId());
		organizeInfoEntity.setOrganizeName(userEntity.getUsername());
		organizeInfoEntity.setMobile(userEntity.getMobile());
		organizeInfoEntity.setEmail(userEntity.getEmail());
		sysOrganizeInfoDao.insert(organizeInfoEntity);

		//检查角色是否越权
		checkRole(userEntity);

		//保存用户与角色关系
		List<String> roleList = new LinkedList<>();
		roleList.add(Constant.ADMIN);
		sysUserRoleService.saveOrUpdate(userEntity.getUserId(), roleList);
	}

    @Override
	@Transactional
    public void delete(String userId) {
		//删除基本信息
        userDao.deleteById(userId);
        //删除角色关系表
		sysUserRoleService.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_id",userId));
		//删除organizeInfoEntity表
		sysOrganizeInfoDao.delete(new QueryWrapper<SysOrganizeInfoEntity>().eq("user_id",userId));

    }

	@Override
	public List<SysDelegationUserInfoVOEntity> listByDelegation(String delegation) {


		return userDao.listByDelegation(delegation);
	}


	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId().equals(Constant.SUPER_ADMIN)){
			return ;
		}

		//查询用户创建的角色列表
		List<String> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}
